#!/bin/bash

# 提示用户输入Python版本
read -p "请输入你想要安装的Python版本（例如 3.10.12）：" version

# 定义下载链接和文件名
#url="https://mirrors.huaweicloud.com/python/${version}/Python-${version}.tgz"
url="https://mirrors.aliyun.com/python-release/source/Python-${version}.tgz"

filename="Python-${version}.tgz"

echo "安装基础依赖"
sudo apt update
sudo apt install net-tools build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev g++ libpq-dev libsqlite3-dev valgrind patchelf -y

# 下载源码包
echo "开始从 ${url} 下载 Python ${version} 源码包..."
ls|grep $filename || wget $url
if [ $? -ne 0 ]; then
    echo "下载失败，请检查网络或版本号是否正确。"
    exit 1
fi
echo "下载完成。"

# 解压源码包
echo "开始解压源码包..."
tar -zxvf $filename
if [ $? -ne 0 ]; then
    echo "解压失败，请检查文件是否完整。"
    exit 1
fi
echo "解压完成。"

# 进入解压后的目录
source_dir="Python-${version}"
cd $source_dir

# 配置编译选项
echo "开始配置编译选项..."
make clean
./configure --with-ssl --with-valgrind --enable-optimizations --enable-shared --enable-loadable-sqlite-extensions --with-xz --with-lto --with-computed-gotos 
if [ $? -ne 0 ]; then
    echo "配置失败，请检查系统环境。"
    exit 1
fi
echo "配置完成。"

# 编译源码
echo "开始编译源码..."
make
if [ $? -ne 0 ]; then
    echo "编译失败，请检查编译工具和依赖是否安装。"
    exit 1
fi
echo "编译完成。"

# 安装Python
echo "开始安装Python..."
sudo make install
if [ $? -ne 0 ]; then
    echo "安装失败，请检查权限。"
    exit 1
fi
sudo patchelf --set-rpath /usr/local/lib /usr/local/bin/python$(echo $version | cut -d. -f1-2)
echo "Python ${version} 安装完成。"    
